package com.example.webdemo.controller;

//登录控制，并未与前端输入接口联动

import com.example.webdemo.bean.customer;
import com.example.webdemo.dto.LoginRequest;
import com.example.webdemo.dto.LoginResponse;
import com.example.webdemo.service.AuthenticationService;
import com.example.webdemo.service.CustomerService;
import com.example.webdemo.util.JsonResult;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.Logger;

import java.util.*;

@RestController
@RequestMapping("/login")
public class LoginController {

    // 添加 Log4j2 日志记录器
    private static final Logger logger = LogManager.getLogger(AuthenticationService.class);

    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private CustomerService customerService;

    @PostMapping("/login")
    public JsonResult<LoginResponse> login(@RequestBody LoginRequest loginRequest,HttpSession session) {
        logger.debug("登录控制开始: {}", loginRequest.getUsername());
        try {
            LoginResponse response = authenticationService.login(loginRequest);
            logger.debug("登录控制结束: {}", loginRequest.getUsername());
            session.setAttribute("token", response.getToken());
            session.setAttribute("userid", response.getUserId());
            session.setAttribute("username", response.getUsername());
            session.setAttribute("realname", response.getRealName());
            logger.info("用户生成Token: {}", session.getAttribute("token"));
            return JsonResult.success(response);
        } catch (Exception e) {
            return JsonResult.error("登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/customers")
    public JsonResult<List<customer>> getAllCustomers() {
        return JsonResult.success(customerService.getAllCustomers());
    }

    // 在LoginController中添加
    @PostMapping("/reset-password")
    public JsonResult<String> resetPassword(@RequestParam String email) {
        try {
            // 实现密码重置逻辑
            authenticationService.resetPassword(email);
            return JsonResult.success("重置链接已发送到您的邮箱");
        } catch (Exception e) {
            return JsonResult.error("重置失败: " + e.getMessage());
        }
    }
}
